<template>
  <div style="height: 100vh; display: flex; align-items: center; justify-content: center" class="container">
    <div style="display: flex; background-color: white; width: 50%; border-radius: 5px; overflow: hidden">
      <div style="flex: 1">
        <img src="@/assets/login.png" alt="" style="width: 100%">
      </div>
      <div style="flex: 1; display: flex; align-items: center; justify-content: center">
        <el-form :model="user" style="width: 80%" :rules="rules" ref="loginRef">
          <div style="font-size: 30px; font-weight: bold; text-align: center; margin-bottom: 20px">天翼假勤管理系统</div>
          <el-form-item prop="username">
            <div style="display: flex">
              <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入账号" v-model="user.username"></el-input>
              <el-button style="margin-left: 5px" type="primary" @click="getCaptcha" :disabled="timeDelay">{{btntxt}}</el-button>
            </div>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input prefix-icon="el-icon-lock" size="medium" show-password placeholder="请输入验证码" v-model="user.captcha"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="info" style="width: 100%" @click="login">登 录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie"
import {userLogin} from "@/utils/user";
import {getCaptcha} from "@/utils/captcha";
import {auth} from "@/utils/auth";
import LocalStorage from "@/utils/localStorage";  //登录页引入
export default {
  name: "Login",
  components: {},
  data() {
    return {
      user: {
        username: '',
        captcha: ''
      },
      timeDelay:false,
      time:60,
      btntxt:"点击获取验证码",
      redirect: undefined,
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
        ]
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    let url = window.location.href
    let params = this.queryURLParams(url)
    let appToken = params['appToken']
    if (appToken && Cookies.get('appToken') !== 'logout') {
      auth({},appToken).then(res=>{
        if (res.code === '1') {
          localStorage.setItem("user", JSON.stringify(res.data))  // 存储用户数据
          this.$store.commit('setUserInfo',res.data)
          console.log('state',this.$store.state.userInfo.userInfo)
          this.$router.push({ path: this.redirect || '/' })
          // this.$router.push('/')
          this.$message.success('登录成功')
          console.log('技术支持：云中台研发团队张传琦（15305549335）')
        }else{
          this.$message.error('登录失败')
        }
      }).catch(err=>{
        this.$message.error(err.errMsg)
      })
    }
    console.log('预登录')
  },
  methods: {
    queryURLParams(URL) {
      let url = URL.split("?")[1]
      const urlSearchParams = new URLSearchParams(url)
      const params = Object.fromEntries(urlSearchParams.entries());
      return params
    },
    startTimer() {
      if (this.time > 0) {
        this.timeDelay=true;
        this.time--;
        this.btntxt=this.time+"秒后重新获取";
        setTimeout(this.startTimer, 1000);
      } else{
        this.time=0;
        this.btntxt="点击获取验证码";
        this.timeDelay=false;
      }
    },
    getCaptcha(){
      this.time = 60
      this.startTimer()
      let params={
        username:this.user.username
      }
      getCaptcha(params).then(res=>{
        if(res.code==='1'){
          this.$message.success(res.message)
        }else{
          this.$message.error(res.message)
        }
      })
    },
    login() {
      // this.$router.push('/')
      this.$refs['loginRef'].validate((valid) => {
        if (valid) {
          // 验证通过
          userLogin( this.user).then(res => {
            if (res.code === '1') {
              localStorage.setItem("user", JSON.stringify(res.data))  // 存储用户数据
              this.$store.commit('setUserInfo',res.data)
              LocalStorage.setCookie('ACCESS_TOKEN',JSON.stringify(res.data))
              console.log('state',this.$store.state.userInfo.userInfo)
              this.$router.push('/')
              this.$message.success('登录成功')
              console.log('技术支持：云中台研发团队张传琦（15305549335）')
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  background-image:url("@/assets/高清.jpg");
  background-size:cover;
  background-repeat: no-repeat
}
</style>
